package cc.mrbird.febs.item.dao;

import cc.mrbird.febs.item.domain.ItemBean;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface ItemMapper extends BaseMapper<ItemBean> {
    @Select("select b.*, a.similar from " +
            "(select itemid2, similar from item_df where itemid1 = #{item.itemid}) a," +
            "(select a.*, b.item_id is_like from item a left join (select item_id from user_item where user_id = #{item.systemUserId}) b on a.itemid = b.item_id) b where a.itemid2 = b.itemid order by a.similar desc")
    IPage<ItemBean> listItemById(Page page, @Param("item") ItemBean itemBean);

    /**
     * 列表管理
     * @param page
     * @param itemBean
     * @return
     */
    @Select("select * from (select a.*, b.rating, c.item_id is_like from item a left join (select item_id, rating from ratings where user_id = #{item.systemUserId}) b on a.itemid = b.item_id left join (select item_id from user_item where user_id = #{item.systemUserId}) c on a.itemid = c.item_id) a where item_name like concat(concat('%', #{item.itemName}), '%')")
    IPage<ItemBean> listItemByName(Page page, @Param("item") ItemBean itemBean);

    @Select("select b.*, a.pref from " +
            "(select itemid, pref from user_cf where userid = #{item.userid}) a," +
            "(select a.*, b.item_id is_like from item a left join (select item_id from user_item where user_id = #{item.systemUserId}) b on a.itemid = b.item_id) b where a.itemid = b.itemid order by a.pref desc")
    IPage<ItemBean> listItemByUser(Page page, @Param("item") ItemBean itemBean);

    @Select("select * from item")
    List<ItemBean> listItem();

    @Select("select a.*, b.item_id is_like from item a, (select item_id from user_item where user_id = #{item.systemUserId}) b " +
            "where a.itemid = b.item_id and item_name like concat(concat('%', #{item.itemName}), '%')")
    IPage<ItemBean> listLikeItem(Page page, @Param("item") ItemBean itemBean);

    @Select("select count(1) from ratings where user_id=#{item.userid} and item_id=#{item.itemid}")
    int countRate(@Param("item") ItemBean itemBean);

    @Insert("insert into ratings(user_id, item_id, rating) values (#{item.userid}, #{item.itemid}, #{item.rating})")
    void insertRate(@Param("item") ItemBean itemBean);

    @Update("update ratings set rating=#{item.rating} where user_id=#{item.userid} and item_id=#{item.itemid}")
    void updateRate(@Param("item") ItemBean itemBean);
}
